package com.cp.mtq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cp.mtq.bean.Result;
import com.cp.mtq.bean.SearchResult;
import com.cp.mtq.entity.MtqImage;
import com.cp.mtq.entity.MtqIntroduce;
import com.cp.mtq.entity.MtqRegion;
import com.cp.mtq.service.MtqImageService;
import com.cp.mtq.service.MtqIntroduceService;
import com.cp.mtq.service.MtqRegionService;
import com.cp.mtq.utils.ResultUtil;
import com.mysql.jdbc.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/introduce")
public class MtqIntroduceController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MtqIntroduceService introduceService;
    @Autowired
    private MtqRegionService regionService;
    @Autowired
    private MtqImageService imageService;

    @GetMapping("regions")
    public Result regions(){
        List<MtqRegion> list = regionService.list();
        return new ResultUtil<>().setData(list);
    }
    @GetMapping("list")
    public Result introduces(MtqIntroduce introduceParam, @RequestParam(defaultValue = "1") Long target, @RequestParam(defaultValue = "6") Long size){
        Page<MtqIntroduce> page = new Page<>();
        page.setCurrent(target);
        page.setDesc("create_time");
        page.setSize(size);
        QueryWrapper<MtqIntroduce> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("used_flag", "1");
        if(introduceParam.getRegionId()!=null) queryWrapper.eq("region_id", introduceParam.getRegionId());
        if(!StringUtils.isNullOrEmpty(introduceParam.getAuthor())) queryWrapper.like("author", introduceParam.getAuthor());
        if(!StringUtils.isNullOrEmpty(introduceParam.getTitle())) queryWrapper.like("title", introduceParam.getTitle());
        page = (Page) introduceService.page(page, queryWrapper);
        page.getRecords().parallelStream().forEach(e->{
            List<MtqImage> images = imageService.list(new QueryWrapper<MtqImage>().eq("introduce_id", e.getId()));
            e.setImages(images);
            String s1 = e.getContent()
                    .replaceAll("<[\\S\\s]*?>", "")
                    .replaceAll("[\r\n]", "");
            int end = 60;
            if(s1.length()<50) end = s1.length()/2;
            e.setContent(
                    s1.substring(0,end)+".."
            );
            String s = redisTemplate.opsForValue().get("read:count::" + e.getId());
            if(s==null) s="0";
            e.setReadCount(Integer.valueOf(s));
        });
        return new ResultUtil<>().setData(page);
    }
    @GetMapping("detail")
    public Result detail(String id){
        MtqIntroduce introduce = introduceService.getById(id);
        introduce.setImages(imageService.list(new QueryWrapper<MtqImage>().eq("introduce_id", id)));
        introduce.setReadCount(Math.toIntExact(redisTemplate.opsForValue().increment("read:count::" + id)));
        return new ResultUtil<>().setData(introduce);
    }

    @PostMapping("save")
    public boolean save(MtqIntroduce introduce, String imagesStr){

        introduceService.save(introduce);
        String[] images = imagesStr.split(",");
        ArrayList<MtqImage> imagelist = new ArrayList<>();
        MtqImage mtqImage;
        for(String url: images){
            mtqImage = new MtqImage();
            mtqImage.setIntroduceId(introduce.getId());
            mtqImage.setUrl(url);
            imagelist.add(mtqImage);
        }
        imageService.saveBatch(imagelist);
        return true;
    }
    @PostMapping("update")
    public boolean update(MtqIntroduce introduce){
        return introduceService.updateById(introduce);
    }
    @PostMapping("changeStatus")
    public boolean changeStatus(String id, int status){
        MtqIntroduce introduce = introduceService.getById(id);
        introduce.setUsedFlag(status);
        return introduceService.updateById(introduce);
    }
    @PostMapping("remove")
    public boolean remove(String id){
        return introduceService.removeById(id);
    }
    @GetMapping("list2")
    public SearchResult introduces2(MtqIntroduce introduceParam, @RequestParam(name = "offset", defaultValue = "1") Integer offset,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer size){
        Page<MtqIntroduce> page = new Page<>();
        page.setCurrent(offset);
        page.setSize(size);
        page.setDesc("id");
        QueryWrapper<MtqIntroduce> queryWrapper = new QueryWrapper<>();
        if(introduceParam.getUsedFlag()!=null) queryWrapper.eq("used_flag", introduceParam.getUsedFlag());
        if(introduceParam.getRegionId()!=null&&introduceParam.getRegionId()>0) queryWrapper.eq("region_id", introduceParam.getRegionId());
        if(!StringUtils.isNullOrEmpty(introduceParam.getAuthor())) queryWrapper.like("author", introduceParam.getAuthor());
        if(!StringUtils.isNullOrEmpty(introduceParam.getTitle())) queryWrapper.like("title", introduceParam.getTitle());
        page = (Page) introduceService.page(page, queryWrapper);
        page.getRecords().parallelStream().forEach(e->{
            String s = redisTemplate.opsForValue().get("read:count::" + e.getId());
            if(s==null) s="0";
            e.setReadCount(Integer.valueOf(s));
            e.setRegion(regionService.getById(e.getRegionId()).getName());
            //e.setContent("");
        });
        SearchResult searchResult = new SearchResult();
        searchResult.setCurrentPage((int) page.getCurrent());
        searchResult.setRows(page.getRecords());
        searchResult.setTotal((int) page.getTotal());
        searchResult.setTotalPages((int) page.getPages());
        return searchResult;
    }
}
